package cn.janyd.action;

import cn.janyd.action.ui.GeneratorDialog;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

/**
 * @author Janyd
 */
public class GeneratorAction extends AnAction {

    private final GeneratorService generatorService = new GeneratorService();

    @SneakyThrows
    @Override
    public void actionPerformed(AnActionEvent event) {

        PsiElement[] psiElements = event.getData(LangDataKeys.PSI_ELEMENT_ARRAY);
        if (psiElements == null || psiElements.length == 0) {
            return;
        }
        Project project = event.getProject();
        if (project == null) {
            return;
        }
        DumbService dumbService = DumbService.getInstance(project);
        if (dumbService.isDumb()) {
            dumbService.showDumbModeNotification("DataObjectGenerator plugin is not available during indexing");
            return;
        }

//        System.out.println(project);

        GeneratorDialog dialog = new GeneratorDialog(project);
        dialog.show();

        if (dialog.isOK()) {
            ConfigBuilder configBuilder = dialog.getConfigBuilder();
            String projectBasePath = project.getBasePath();
            if (StringUtils.isBlank(projectBasePath)) {
                return;
            }

            generatorService.generate(configBuilder, project, psiElements);
        }
    }

}
